4. Clustering and Classification

The topics of this week - clutering and classification - are visual tools for the exploration of statistical data. Clustering means that some data points are closer to each other than some other points: they are clustered. Once we have clustered successfully, we can try to classify new observations to these clusters, thus validating the results of clustering.

Below are all the codes, my interpretations and explanations for this week’s data analysis exercises.

Part 1 - General Housekeeping

As in last week, I created a new RMarkdown file and save it as an empty file named ‘chapter4.Rmd’. Then I included this file as a child file in my ‘index.Rmd’ file, and as a result you are now reading this.

I also accessed some packages that I might need later.

library(ggplot2); library(GGally); library(corrplot); library(tidyr); library(dplyr)

Part 2 - Loading the Boston data

To load and explore the Boston data, I first needed to access the MASS package, and then load the “Boston” data. Below is the structure and summary of the data, and also a matrix of the variables.

# access the MASS package
library(MASS)

# load the data
data("Boston")

# explore the dataset
str(Boston)
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...

The Boston data set is a data frame with 506 observations of 14 variables. The data examines housing values in the suburbs of Boston. The variables are all numeric, with two variables being integer types.

A link to details about the Boston dataset can be seen here.

Here is the source of the data:

Harrison, D. and Rubinfeld, D.L. (1978) Hedonic prices and the demand for clean air. < em >J. Environ. Economics and Management < b >5, 81-102.

Belsley D.A., Kuh, E. and Welsch, R.E. (1980) < em >Regression Diagnostics. Identifying Influential Data and Sources of Collinearity. New York: Wiley.

Part 3 - Exploring the Boston data

Below is a graphical overview of the data and the summaries of the variables in the data.

summary(Boston)
##       crim                zn             indus            chas        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   Min.   :0.00000  
##  1st Qu.: 0.08204   1st Qu.:  0.00   1st Qu.: 5.19   1st Qu.:0.00000  
##  Median : 0.25651   Median :  0.00   Median : 9.69   Median :0.00000  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14   Mean   :0.06917  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10   3rd Qu.:0.00000  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74   Max.   :1.00000  
##       nox               rm             age              dis        
##  Min.   :0.3850   Min.   :3.561   Min.   :  2.90   Min.   : 1.130  
##  1st Qu.:0.4490   1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100  
##  Median :0.5380   Median :6.208   Median : 77.50   Median : 3.207  
##  Mean   :0.5547   Mean   :6.285   Mean   : 68.57   Mean   : 3.795  
##  3rd Qu.:0.6240   3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188  
##  Max.   :0.8710   Max.   :8.780   Max.   :100.00   Max.   :12.127  
##       rad              tax           ptratio          black       
##  Min.   : 1.000   Min.   :187.0   Min.   :12.60   Min.   :  0.32  
##  1st Qu.: 4.000   1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38  
##  Median : 5.000   Median :330.0   Median :19.05   Median :391.44  
##  Mean   : 9.549   Mean   :408.2   Mean   :18.46   Mean   :356.67  
##  3rd Qu.:24.000   3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23  
##  Max.   :24.000   Max.   :711.0   Max.   :22.00   Max.   :396.90  
##      lstat            medv      
##  Min.   : 1.73   Min.   : 5.00  
##  1st Qu.: 6.95   1st Qu.:17.02  
##  Median :11.36   Median :21.20  
##  Mean   :12.65   Mean   :22.53  
##  3rd Qu.:16.95   3rd Qu.:25.00  
##  Max.   :37.97   Max.   :50.00
pairs(Boston)

The variable of interest here, as the data looks at housing values, is medv. It shows the median value of owner-occupied homes in $1000s.

The values for medvvary from 5 to 50, witha mean value of 22.53. medv correlates quite well with all the variables (apart from the Charles River dummy variable), but most strongly with the average number of rooms per dwelling rm(0.695) and lower status of the population lstat(obviously with a negative correlation of -0.738).

Let’s look at a way of plotting the correlations, this time from the corrplotpackage. Also, the funstion cor() can be used to craete a correlation matrix of the data.

# calculate the correlation matrix and round it
cor_matrix<-cor(Boston) %>% round(digits = 2)

# print the correlation matrix
cor_matrix
##          crim    zn indus  chas   nox    rm   age   dis   rad   tax
## crim     1.00 -0.20  0.41 -0.06  0.42 -0.22  0.35 -0.38  0.63  0.58
## zn      -0.20  1.00 -0.53 -0.04 -0.52  0.31 -0.57  0.66 -0.31 -0.31
## indus    0.41 -0.53  1.00  0.06  0.76 -0.39  0.64 -0.71  0.60  0.72
## chas    -0.06 -0.04  0.06  1.00  0.09  0.09  0.09 -0.10 -0.01 -0.04
## nox      0.42 -0.52  0.76  0.09  1.00 -0.30  0.73 -0.77  0.61  0.67
## rm      -0.22  0.31 -0.39  0.09 -0.30  1.00 -0.24  0.21 -0.21 -0.29
## age      0.35 -0.57  0.64  0.09  0.73 -0.24  1.00 -0.75  0.46  0.51
## dis     -0.38  0.66 -0.71 -0.10 -0.77  0.21 -0.75  1.00 -0.49 -0.53
## rad      0.63 -0.31  0.60 -0.01  0.61 -0.21  0.46 -0.49  1.00  0.91
## tax      0.58 -0.31  0.72 -0.04  0.67 -0.29  0.51 -0.53  0.91  1.00
## ptratio  0.29 -0.39  0.38 -0.12  0.19 -0.36  0.26 -0.23  0.46  0.46
## black   -0.39  0.18 -0.36  0.05 -0.38  0.13 -0.27  0.29 -0.44 -0.44
## lstat    0.46 -0.41  0.60 -0.05  0.59 -0.61  0.60 -0.50  0.49  0.54
## medv    -0.39  0.36 -0.48  0.18 -0.43  0.70 -0.38  0.25 -0.38 -0.47
##         ptratio black lstat  medv
## crim       0.29 -0.39  0.46 -0.39
## zn        -0.39  0.18 -0.41  0.36
## indus      0.38 -0.36  0.60 -0.48
## chas      -0.12  0.05 -0.05  0.18
## nox        0.19 -0.38  0.59 -0.43
## rm        -0.36  0.13 -0.61  0.70
## age        0.26 -0.27  0.60 -0.38
## dis       -0.23  0.29 -0.50  0.25
## rad        0.46 -0.44  0.49 -0.38
## tax        0.46 -0.44  0.54 -0.47
## ptratio    1.00 -0.18  0.37 -0.51
## black     -0.18  1.00 -0.37  0.33
## lstat      0.37 -0.37  1.00 -0.74
## medv      -0.51  0.33 -0.74  1.00
# visualize the correlation matrix
corrplot(cor_matrix, method="square", type="lower", cl.pos="b", tl.pos="d", tl.cex = 0.6)

The corrplotis a really neat visualization method. Positive correlations are displayed in blue and negative correlations in red color. Color intensity and the size of the square are proportional to the correlation coefficients. As we can see from above, this gives us a quick visual way of confirming what we knew from before lstathas a strong negative correlation with medvand rm has a strong positive correlation with medv. At a glance, we can see that there are a handful of other strong positive and negative correlations in the matrix too.

Part 4 - Creating Training and Test Sets

Now we need to scale the data. This is done by subtracting the column means from the corresponding columns and dividing the difference with standard deviation. \[scaled(x)=\frac{x-mean(x)}{sd(x)}\] The dataset is then standardized, and below I have printed out a summary of the scaled data.

# center and standardize variables
boston_scaled <- scale(Boston)

# summaries of the scaled variables
summary(boston_scaled)
##       crim                 zn               indus        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202  
##       chas              nox                rm               age         
##  Min.   :-0.2723   Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331  
##  1st Qu.:-0.2723   1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366  
##  Median :-0.2723   Median :-0.1441   Median :-0.1084   Median : 0.3171  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.:-0.2723   3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059  
##  Max.   : 3.6648   Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164  
##       dis               rad               tax             ptratio       
##  Min.   :-1.2658   Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047  
##  1st Qu.:-0.8049   1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876  
##  Median :-0.2790   Median :-0.5225   Median :-0.4642   Median : 0.2746  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6617   3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058  
##  Max.   : 3.9566   Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372  
##      black             lstat              medv        
##  Min.   :-3.9033   Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.: 0.2049   1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median : 0.3808   Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4332   3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 0.4406   Max.   : 3.5453   Max.   : 2.9865
# class of the boston_scaled object
class(boston_scaled)
## [1] "matrix"
# change the object to data frame
boston_scaled <- as.data.frame(boston_scaled)

How did the variables change? They have changed per the scaled(x) equation above. It is worth noting that in this new summary, all the mean values are 0.

We can create a categorical variable from a continuous one, and we will do that with the crime rate in the Boston dataset (from the scaled crime rate). We will cut the crimvariable by quantiles to get the high, low and middle rates of crime into their own categories. The quantiles are used as the break points in the new categorical variable. The old crime rate variable is dropped from the dataset.

# summary of the scaled crime rate
summary(boston_scaled$crim)
##      Min.   1st Qu.    Median      Mean   3rd Qu.      Max. 
## -0.419367 -0.410563 -0.390280  0.000000  0.007389  9.924110
# create a quantile vector of crim and print it
bins <- quantile(boston_scaled$crim)
bins
##           0%          25%          50%          75%         100% 
## -0.419366929 -0.410563278 -0.390280295  0.007389247  9.924109610
# create a categorical variable 'crime'
crime <- cut(boston_scaled$crim, breaks = bins, include.lowest = TRUE, labels = c("low", "med_low", "med_high", "high"))

# look at the table of the new factor crime
table(crime)
## crime
##      low  med_low med_high     high 
##      127      126      126      127
# remove original crim from the dataset
boston_scaled <- dplyr::select(boston_scaled, -crim)

# add the new categorical value to scaled data
boston_scaled <- data.frame(boston_scaled, crime)

Next, we will divide the dataset to training and test sets, so that 80% of the data belongs to the training set.

# number of rows in the Boston dataset 
n <- nrow(boston_scaled)

# choose randomly 80% of the rows
ind <- sample(n,  size = n * 0.8)

# create train set
train <- boston_scaled[ind,]

# create test set 
test <- boston_scaled[-ind,]

# save the correct classes from test data
correct_classes <- test$crime

# remove the crime variable from test data
test <- dplyr::select(test, -crime)

Part 5 - Linear Discriminant Analysis

Next we will look at linear discriminant analysis. It is a classification and dimension reduction method that is closely related to logictic regression (from last week) and principal component analysis (next week). It can be used to find variables that discriminate or separate the classes best, or it can be used to predict the classes of new data.

First, we will fit the linear discriminant analysis on the training set created in the previous step. We will use the categorical crime rate as the target variable and all the other variables are predictor variables. Then we will draw the LDA (bi)plot.

# linear discriminant analysis
lda.fit <- lda(crime ~ ., data = train)

# print the lda.fit object
lda.fit
## Call:
## lda(crime ~ ., data = train)
## 
## Prior probabilities of groups:
##       low   med_low  med_high      high 
## 0.2500000 0.2425743 0.2574257 0.2500000 
## 
## Group means:
##                   zn      indus        chas        nox          rm
## low       0.89756396 -0.8816979 -0.07742312 -0.8643889  0.45374805
## med_low  -0.07596969 -0.2387191 -0.03128211 -0.5576091 -0.14696031
## med_high -0.40395960  0.1915480  0.18195173  0.4019253  0.03385726
## high     -0.48724019  1.0171306 -0.03844192  1.0716148 -0.36115430
##                 age        dis        rad        tax     ptratio
## low      -0.8589289  0.8533994 -0.6850891 -0.7505443 -0.45645807
## med_low  -0.2697903  0.3802906 -0.5400630 -0.4462313 -0.03507791
## med_high  0.4222436 -0.3885609 -0.4264107 -0.3197575 -0.28058751
## high      0.8199108 -0.8553809  1.6379981  1.5139626  0.78062517
##                black       lstat       medv
## low       0.38367712 -0.78419629  0.5334079
## med_low   0.30442230 -0.07707680 -0.0348546
## med_high  0.06388963  0.03799993  0.1133176
## high     -0.82812475  0.86634735 -0.6878117
## 
## Coefficients of linear discriminants:
##                 LD1          LD2         LD3
## zn       0.13860720  0.679722653 -0.93788144
## indus   -0.01213759 -0.115763348  0.36419943
## chas    -0.01656663 -0.045263394  0.07249929
## nox      0.39956233 -0.809558102 -1.24119874
## rm       0.02159464 -0.018182834 -0.14288394
## age      0.23358885 -0.329941055 -0.09028291
## dis     -0.13339459 -0.199396893  0.46126410
## rad      3.33690687  0.954069149 -0.27760202
## tax      0.04350042 -0.001220349  0.72910183
## ptratio  0.16978012 -0.082049394 -0.19844896
## black   -0.10615961  0.048401654  0.09441656
## lstat    0.19496159 -0.213998115  0.59402347
## medv     0.09105576 -0.451048029  0.01036654
## 
## Proportion of trace:
##    LD1    LD2    LD3 
## 0.9542 0.0340 0.0118

Now, I will try to explain the above LDA model output with the help of a very useful video that can be found here. Look for the part starting at 02:46.

First at the top we have the prior probabilities of groups. These are simply the number of observations in each class divided by the number of observations in the whole dataset.

The group means have the value for every variable and for every class. The means differ between the classes.

Then there are the coefficients of the linear discriminants. There is a coefficient for each of the variables. We have four target variables, and therefore three linear discriminants.

The proportion of trace is the between-group variance. In our model, Linear Discriminant 1 explains almost 95% of the between-group variance.

# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "orange", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

# target classes as numeric
classes <- as.numeric(train$crime)

# plot the lda results
plot(lda.fit, dimen = 2, col = classes, pch = classes)
lda.arrows(lda.fit, myscale = 1.5)

Part 6 - Predict with the LDA Model

The data was split earlier so that we now have the test set and the correct class labels. Now we will predict the classes with the LDA model on the test data. Based on the trained model, LDA calculates the probabilites for the new observation for belonging in each of the classes. The observation is classified to the class of the highest probability. The probabilities are estimated using Bayes Theorem.

The results are cross tabulated with the crime categories from the test set.

Save the crime categories from the test set and then remove the categorical crime variable from the test dataset

# predict classes with test data
lda.pred <- predict(lda.fit, newdata = test)

# cross tabulate the results
tt <- table(correct = correct_classes, predicted = lda.pred$class)
tt
##           predicted
## correct    low med_low med_high high
##   low       18       5        3    0
##   med_low    6      15        7    0
##   med_high   0       5       15    2
##   high       0       0        0   26
error = sum(tt[row(tt) != col(tt)]) / sum(tt)
error
## [1] 0.2745098
summary(test)
##        zn               indus              chas         
##  Min.   :-0.48724   Min.   :-1.4018   Min.   :-0.27233  
##  1st Qu.:-0.48724   1st Qu.:-0.9554   1st Qu.:-0.27233  
##  Median :-0.48724   Median :-0.3756   Median :-0.27233  
##  Mean   : 0.07857   Mean   :-0.1001   Mean   :-0.04074  
##  3rd Qu.: 0.37030   3rd Qu.: 1.0150   3rd Qu.:-0.27233  
##  Max.   : 3.58609   Max.   : 1.5674   Max.   : 3.66477  
##       nox                 rm                age          
##  Min.   :-1.46443   Min.   :-3.87641   Min.   :-2.20524  
##  1st Qu.:-0.92076   1st Qu.:-0.58906   1st Qu.:-1.21852  
##  Median :-0.19585   Median :-0.09911   Median : 0.09148  
##  Mean   :-0.07926   Mean   : 0.01499   Mean   :-0.13268  
##  3rd Qu.: 0.64339   3rd Qu.: 0.46664   3rd Qu.: 0.81798  
##  Max.   : 2.72965   Max.   : 3.55153   Max.   : 1.11639  
##       dis                rad                tax           
##  Min.   :-1.26230   Min.   :-0.98187   Min.   :-1.277090  
##  1st Qu.:-0.83252   1st Qu.:-0.63733   1st Qu.:-0.797968  
##  Median :-0.33209   Median :-0.52248   Median :-0.443446  
##  Mean   : 0.03277   Mean   : 0.01009   Mean   :-0.001174  
##  3rd Qu.: 0.70867   3rd Qu.: 1.65960   3rd Qu.: 1.529413  
##  Max.   : 3.28405   Max.   : 1.65960   Max.   : 1.529413  
##     ptratio              black              lstat         
##  Min.   :-2.704702   Min.   :-3.86850   Min.   :-1.50301  
##  1st Qu.:-0.753152   1st Qu.: 0.27861   1st Qu.:-0.82349  
##  Median : 0.343873   Median : 0.40086   Median :-0.35122  
##  Mean   :-0.001197   Mean   : 0.08246   Mean   :-0.04604  
##  3rd Qu.: 0.805778   3rd Qu.: 0.44062   3rd Qu.: 0.50615  
##  Max.   : 1.267684   Max.   : 0.44062   Max.   : 3.54526  
##       medv         
##  Min.   :-1.90634  
##  1st Qu.:-0.43577  
##  Median :-0.07968  
##  Mean   : 0.07084  
##  3rd Qu.: 0.26282  
##  Max.   : 2.98650

As the cross tabulation shows, the LDA model performs exceptionally well only for high when predicting on new (test) data. For rest of the classes, the predictions are roughly 50% - 60% correct. Overall, the error rate is 33%. It is worth noting here that because of the way that the observations are divided randomly, we will see a slightly different table every time we run the function.

Part 7 - K-means Algorithm

Now we will look at clustering, and we will start with distance measures. First, we need to reload the Boston dataset and standardize the dataset.

library(MASS)
data('Boston')

Now we will scale the Bostonvariables to get comparable distances.

# center and standardize variables
boston_K_scaled <- scale(Boston)

# summaries of the scaled variables
summary(boston_K_scaled)
##       crim                 zn               indus        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202  
##       chas              nox                rm               age         
##  Min.   :-0.2723   Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331  
##  1st Qu.:-0.2723   1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366  
##  Median :-0.2723   Median :-0.1441   Median :-0.1084   Median : 0.3171  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.:-0.2723   3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059  
##  Max.   : 3.6648   Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164  
##       dis               rad               tax             ptratio       
##  Min.   :-1.2658   Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047  
##  1st Qu.:-0.8049   1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876  
##  Median :-0.2790   Median :-0.5225   Median :-0.4642   Median : 0.2746  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6617   3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058  
##  Max.   : 3.9566   Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372  
##      black             lstat              medv        
##  Min.   :-3.9033   Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.: 0.2049   1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median : 0.3808   Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4332   3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 0.4406   Max.   : 3.5453   Max.   : 2.9865
# class of the boston_scaled object
class(boston_K_scaled)
## [1] "matrix"
# change the object to data frame
boston_K_scaled <- as.data.frame(boston_K_scaled)

Now we will calculate the distances between the observations. We will use the dist()function for this, and by default it will use Euclidean distance measure to create a distance matrix. We will also look at the Manhattan method.

# euclidean distance matrix
dist_eu <- dist(boston_K_scaled)

# look at the summary of the distances
summary(dist_eu)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.1343  3.4625  4.8241  4.9111  6.1863 14.3970
# manhattan distance matrix
dist_man <- dist(boston_K_scaled, method = 'manhattan')

# look at the summary of the distances
summary(dist_man)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.2662  8.4832 12.6090 13.5488 17.7568 48.8618

K-means is one of the best known clustering methods, and it is an unsupervised one. It assigns obsrvations to clusters based on the similarities of the objects. We will next run a k-means algorithm on the dataset. We will use 4 centers to begin with. This could in theory be any number though, hence the K.

# k-means clustering
km <-kmeans(boston_K_scaled, centers = 4)

# plot the Boston dataset with clusters
pairs(boston_K_scaled, col = km$cluster)

But now the question arises: what is the optimal number of clusters? In other words, we need to determine the K. There are more than one way to skin the proverbial cat here, but we will look at how the total of within cluster sum of squares or WCSS behaves when we change the number of clusters. The WCSS is calculated as follows:

\(WCSS=\sum^N_{i} (X_i-centroid)^2\)

We will achieve this by plotting the number of clusters and the total WCSS. Once the WCSS drops radically, we have the optimal number of clusters. So, let’s see where we get our radical drop!

set.seed(123) #K-means might produce different results every time, because it randomly assigns the initial cluster centers. This function is used to deal with that.

# determine the number of clusters
k_max <- 10

# calculate the total within sum of squares
twcss <- sapply(1:k_max, function(k){kmeans(boston_K_scaled, k)$tot.withinss})

# visualize the results
qplot(x = 1:k_max, y = twcss, geom = 'line')

In this case, two clusters seems optimal. We will therefore run kmeans()again with two clusters and visualize the results. I will split the pairs plot into two separate ones, for more readable results. I was going to use ggpairs but drawing the plot took soooooo long!

# k-means clustering
km <-kmeans(boston_K_scaled, centers = 2, nstart = 20)
km
## K-means clustering with 2 clusters of sizes 177, 329
## 
## Cluster means:
##         crim         zn      indus         chas        nox         rm
## 1  0.7238295 -0.4872402  1.1425514 -0.005407018  1.0824279 -0.4547830
## 2 -0.3894158  0.2621323 -0.6146857  0.002908943 -0.5823397  0.2446705
##          age        dis        rad        tax    ptratio      black
## 1  0.8051309 -0.8439539  1.0834228  1.1693521  0.5471636 -0.6101842
## 2 -0.4331555  0.4540421 -0.5828749 -0.6291043 -0.2943707  0.3282754
##        lstat       medv
## 1  0.8421083 -0.6566834
## 2 -0.4530491  0.3532917
## 
## Clustering vector:
##   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
##  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   1   2   2   2 
##  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
##  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
##  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
##  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   1   1   1   2 
## 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   2   2   1   2   2 
## 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 
##   2   2   2   1   2   1   2   2   1   1   2   2   2   2   2   2   2   2 
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   1   1   1   1 
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 
##   1   1   1   1   1   1   1   2   2   2   2   2   2   2   2   2   2   2 
## 505 506 
##   2   2 
## 
## Within cluster sum of squares by cluster:
## [1] 1890.637 2686.045
##  (between_SS / total_SS =  35.3 %)
## 
## Available components:
## 
## [1] "cluster"      "centers"      "totss"        "withinss"    
## [5] "tot.withinss" "betweenss"    "size"         "iter"        
## [9] "ifault"
# plot the Boston dataset with clusters
pairs(boston_K_scaled[1:5], col = km$cluster)

pairs(boston_K_scaled[6:10], col = km$cluster)

The first cluster is composed of 177 observations, and the second of 329. Only 35.3% of the total variance in the data set is explained by the clustering, and this indicates a poor fit.

Bonus

Perform k-means on the original Boston data with some reasonable number of clusters (> 2) (I did 3). Remember to standardize the dataset.

library(MASS)
data('Boston')
# center and standardize variables
boston_K2_scaled <- scale(Boston)

# summaries of the scaled variables
summary(boston_K2_scaled)
##       crim                 zn               indus        
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202  
##       chas              nox                rm               age         
##  Min.   :-0.2723   Min.   :-1.4644   Min.   :-3.8764   Min.   :-2.3331  
##  1st Qu.:-0.2723   1st Qu.:-0.9121   1st Qu.:-0.5681   1st Qu.:-0.8366  
##  Median :-0.2723   Median :-0.1441   Median :-0.1084   Median : 0.3171  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.:-0.2723   3rd Qu.: 0.5981   3rd Qu.: 0.4823   3rd Qu.: 0.9059  
##  Max.   : 3.6648   Max.   : 2.7296   Max.   : 3.5515   Max.   : 1.1164  
##       dis               rad               tax             ptratio       
##  Min.   :-1.2658   Min.   :-0.9819   Min.   :-1.3127   Min.   :-2.7047  
##  1st Qu.:-0.8049   1st Qu.:-0.6373   1st Qu.:-0.7668   1st Qu.:-0.4876  
##  Median :-0.2790   Median :-0.5225   Median :-0.4642   Median : 0.2746  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.6617   3rd Qu.: 1.6596   3rd Qu.: 1.5294   3rd Qu.: 0.8058  
##  Max.   : 3.9566   Max.   : 1.6596   Max.   : 1.7964   Max.   : 1.6372  
##      black             lstat              medv        
##  Min.   :-3.9033   Min.   :-1.5296   Min.   :-1.9063  
##  1st Qu.: 0.2049   1st Qu.:-0.7986   1st Qu.:-0.5989  
##  Median : 0.3808   Median :-0.1811   Median :-0.1449  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4332   3rd Qu.: 0.6024   3rd Qu.: 0.2683  
##  Max.   : 0.4406   Max.   : 3.5453   Max.   : 2.9865
# class of the boston_scaled object
class(boston_K2_scaled)
## [1] "matrix"
# change the object to data frame
boston_K2_scaled <- as.data.frame(boston_K2_scaled)

# kmeans with 3 clusters
km <-kmeans(boston_K2_scaled, centers = 3, nstart = 20)
km
## K-means clustering with 3 clusters of sizes 164, 236, 106
## 
## Cluster means:
##         crim         zn     indus        chas        nox          rm
## 1  0.8046456 -0.4872402  1.117990  0.01575144  1.1253988 -0.46443119
## 2 -0.3760908 -0.3417123 -0.296848  0.01127561 -0.3345884 -0.09228038
## 3 -0.4075892  1.5146367 -1.068814 -0.04947434 -0.9962503  0.92400834
##           age         dis        rad        tax     ptratio      black
## 1  0.79737580 -0.85425848  1.2219249  1.2954050  0.60580719 -0.6407268
## 2 -0.02966623  0.05695857 -0.5803944 -0.6030198 -0.08691245  0.2863040
## 3 -1.16762641  1.19486951 -0.5983266 -0.6616391 -0.74378342  0.3538816
##        lstat        medv
## 1  0.8719904 -0.68418954
## 2 -0.1801190  0.03577844
## 3 -0.9480974  0.97889973
## 
## Clustering vector:
##   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18 
##   2   2   2   3   3   2   2   2   2   2   2   2   2   2   2   2   2   2 
##  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
##  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54 
##   2   2   2   3   3   3   2   2   2   2   2   2   2   2   2   2   3   3 
##  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72 
##   3   3   3   3   3   2   2   2   2   3   3   3   3   2   2   2   2   2 
##  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90 
##   2   2   2   2   2   2   2   2   3   2   3   2   2   2   2   2   2   2 
##  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 
##   2   2   2   2   2   2   2   3   3   2   2   2   2   2   2   2   2   2 
## 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 
##   2   1   1   1   2   2   2   1   1   1   1   1   1   1   1   1   1   1 
## 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   2   2   2   2   2 
## 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 
##   2   2   2   2   2   2   3   3   3   3   3   3   3   3   3   3   3   3 
## 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 
##   3   3   3   3   3   3   3   2   2   2   2   2   2   2   2   2   2   2 
## 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 
##   2   2   2   2   2   2   2   2   3   3   2   2   3   2   2   2   3   3 
## 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 
##   2   2   2   2   3   3   3   2   3   3   2   2   3   2   3   3   3   3 
## 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 
##   3   3   3   3   3   3   2   2   2   3   3   2   2   2   2   3   3   2 
## 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 
##   2   2   2   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 
##   3   3   3   3   3   2   2   2   2   2   3   3   3   3   3   3   3   2 
## 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 
##   3   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 
##   2   2   2   2   2   2   2   3   3   2   2   2   2   2   2   2   2   3 
## 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 
##   2   3   3   2   2   3   3   3   3   3   3   3   3   3   1   1   1   1 
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 
##   1   1   1   1   1   1   1   2   2   2   2   2   2   2   2   2   2   2 
## 505 506 
##   2   2 
## 
## Within cluster sum of squares by cluster:
## [1] 1717.6354 1394.9385  758.7999
##  (between_SS / total_SS =  45.2 %)
## 
## Available components:
## 
## [1] "cluster"      "centers"      "totss"        "withinss"    
## [5] "tot.withinss" "betweenss"    "size"         "iter"        
## [9] "ifault"

Then we will perform LDA using the clusters as target classes. I will include all the variables in the Boston data in the LDA model.

# access the cluster component in the kmeans data and change it to dataframe
cluster <- km$cluster
cluster <- as.data.frame(cluster)

# Add cluster as a column to boston_K2_scaled, ie. merge the two datasets
bonus_data <- merge(boston_K2_scaled, cluster)

# Create training and test sets

# number of rows in the new dataset 
n <- nrow(bonus_data)

# choose randomly 80% of the rows
ind <- sample(n,  size = n * 0.8)

# create train set
bonus_train <- bonus_data[ind,]

# create test set 
bonus_test <- bonus_data[-ind,]

# Perform LDA
bonus.lda.fit <- lda(cluster ~ ., data = bonus_train)
bonus.lda.fit
## Call:
## lda(cluster ~ ., data = bonus_train)
## 
## Prior probabilities of groups:
##         1         2         3 
## 0.3240231 0.4665036 0.2094733 
## 
## Group means:
##            crim            zn        indus          chas          nox
## 1  0.0016554458 -0.0032816859  0.003320093  0.0016763564  0.002492146
## 2 -0.0001328571  0.0001191164 -0.001702143  0.0033211011 -0.001328476
## 3  0.0027073814  0.0032566259 -0.002699963 -0.0003492724 -0.003361992
##              rm           age           dis           rad          tax
## 1 -0.0007286982  0.0021938001 -0.0047324208  0.0031777545  0.001790359
## 2  0.0017871229 -0.0004809195  0.0006946673 -0.0008323246 -0.001622667
## 3  0.0004078742  0.0003715072  0.0015532537 -0.0010301611 -0.002173667
##        ptratio         black        lstat          medv
## 1  0.002048162 -0.0019099538  0.001157256 -9.782444e-04
## 2 -0.001814217 -0.0004205507 -0.001427496  2.688129e-03
## 3  0.001119350  0.0029583281 -0.000103205  8.492379e-05
## 
## Coefficients of linear discriminants:
##                 LD1         LD2
## crim     0.55072337  0.01850667
## zn       0.44711852  0.76863579
## indus   -0.38179330  0.47500311
## chas    -0.08762222 -0.31334240
## nox     -0.22621821 -0.43228909
## rm       0.02071274  0.01911782
## age      0.71168450  0.04897999
## dis      0.44531388 -1.10905794
## rad     -0.61478741  1.02250037
## tax      0.32188018 -1.24967843
## ptratio  0.19325044  0.28918008
## black    0.36096685  0.36722420
## lstat    0.24613638 -0.41377554
## medv     0.10176888 -0.81631237
## 
## Proportion of trace:
##    LD1    LD2 
## 0.5699 0.4301

Next, we will visualize the results with a biplot (including arrows representing the relationships of the original variables to the LDA solution).

# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "orange", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

# target classes as numeric
classes <- as.numeric(bonus_train$cluster)

# plot the lda results
plot(bonus.lda.fit, dimen = 2, col = classes, pch = classes)
lda.arrows(bonus.lda.fit, myscale = 1.5)

It appears that the most influencial linear separators for the clusters are LDA1 and LDA2. The variables rad and tax represent the most discrimination (their arrows are the longest). The angles between arrows represent the correlations between the variables (small angle = high positive correlation).

Super-Bonus

Run the code below for the (scaled) train data that you used to fit the LDA. The code creates a matrix product, which is a projection of the data points.

model_predictors <- dplyr::select(train, -crime)
# check the dimensions
dim(model_predictors)
## [1] 404  13
dim(lda.fit$scaling)
## [1] 13  3
# matrix multiplication
matrix_product <- as.matrix(model_predictors) %*% lda.fit$scaling
matrix_product <- as.data.frame(matrix_product)

Next, install and access the plotly package. Create a 3D plot (Cool!) of the columns of the matrix product by typing the code below.

library(plotly)
plot_ly(x = matrix_product$LD1, y = matrix_product$LD2, z = matrix_product$LD3, type= 'scatter3d', mode='markers', color=train$crime)

No kidding, this is cool!!

Sadly, this is where I had to stop this week, and I won’t be doing a comparison here. Thanks for reading to the end, and have a good week!